package com.leyou.job.task;

import com.leyou.job.lock.RedisLock;
import com.leyou.job.lock.impl.ReentrantRedisLock;
import com.leyou.job.lock.impl.SimpleRedisLock;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

/**
 * 定时任务类: 定时清理过期未支付的订单
 */
@Slf4j
//@Component
public class CleanOrderTask3_redisLock {

    //@Autowired
    //private StringRedisTemplate redisTemplate;

    @Autowired
    private RedissonClient redissonClient;

    @Scheduled(fixedDelay = 10000L)
    public  void cleanOrder1() throws InterruptedException {
        // 创建锁对象
        // SimpleRedisLock lock = new SimpleRedisLock(redisTemplate, "lock");
        //ReentrantRedisLock lock = new ReentrantRedisLock(redisTemplate, "lock");
        //boolean isLock = lock.lock(50);
        // 获取锁对象
        RLock lock = redissonClient.getLock("lock");
        // 获取锁
        boolean isLock = lock.tryLock();

        // 判断是否获取了锁
        if(!isLock){
            log.warn("【乐优定时微服务】【清理订单】获取锁失败=======");
            return ; // 如果获取不到锁，就不要往下执行
        }
        try{
            // 代码执行到这一步：说明已经获取到锁了
            // TODO 去就执行清理订单的业务即可

            // 模拟清理订单
            log.info("【乐优定时微服务】【清理订单】执行清理订单中");
            // 处理业务实际时间
            Thread.sleep(2000L);

        }catch (Exception e){
            log.error("【乐优定时微服务】【清理订单】出现异常：{}",e.getMessage(), e);
        }finally {
            log.info("【乐优定时微服务】【清理订单】执行清理订单完成，释放锁");
            lock.unlock();
        }


    }
}
